import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import { Card, Table, Form, Space, Button, Modal, DatePicker } from 'antd';
import moment from 'moment';
import "./tableDemo.less"
import TableSearchForm from '@/components/TableSearchForm';
import { getPromoteDetailList } from "@/api/commonApi.js"

const { RangePicker } = DatePicker;
const tableScroll = {
  y: 600
};
const dateFormat = 'YYYY-MM-DD HH:mm:ss';

/**
 * 时间修改modal
 */
const ChangeTimeModal = forwardRef((props, ref) => {
  const [visible, setVisible] = useState(false);
  const [defalTime, setDefalTime] = useState([]);

  useImperativeHandle(ref, () => {
    return {
      showModal(rowDatas) {
        setDefalTime([moment(rowDatas.start_time_local, dateFormat), moment(rowDatas.end_time_local, dateFormat)]);
        setVisible(true);
      }
    }
  })

  const handleOk = () => {
    setVisible(false);
  };

  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <Modal title="修改时间" visible={visible} onOk={handleOk} onCancel={handleCancel}>
      <RangePicker value={defalTime}  showTime/>
    </Modal>
  );
});

const TableDemo = (props) => {
  const [form] = Form.useForm();
  const changeTimeModal = useRef(null);
  
  let [loading, setLoading] = useState(false);
  let [selectedRows, setSelectedRows] = useState([]);
  let [dataSource, setDataSource] = useState([]);
  let [paginationObj, setPaginationObj] = useState({
    showTotal: total => `共 ${total} 条`,
    current: 1,
    pageSize: 20,
    total: 100,
  });

  const tableOnChange = (pagination, filters, sorter) => {
    setPaginationObj({
      ...paginationObj,
      ...pagination
    });
  };

  const columns = [
    {
      title: 'ID号',
      dataIndex: 'id',
    },
    {
      title: '店铺缩写',
      dataIndex: 'shortname',
    },
    {
      title: '币种',
      dataIndex: 'currency',
      render: (text) => {
        return (
          <i className="iconfont hibi-hongseyujing" style={{color:'green'}}></i>
        )
      }
    },
    {
      title: 'ASIN',
      dataIndex: 'asin',
    },
    {
      title: 'SPU',
      dataIndex: 'spu',
    },
    {
      title: '本次申请折扣幅度%',
      dataIndex: 'discount_rate',
    },
    {
      title: '折扣后价格',
      dataIndex: 'discount_price',
    },
    {
      title: '到手价格',
      dataIndex: 'final_price',
    },
    {
      title: '开始时间（当地）',
      dataIndex: 'start_time_local',
      width: 180,
      render: (text, row) => {
        return <>
          {text}<i className="iconfont hibi-bianjiicon" onClick={() => changeTimeModal.current.showModal(row)}></i>
        </>
      }
    },
    {
      title: '操作',
      dataIndex: 'operater',
      render: () => {
        return (
          <Space>
            <Button type="link" size="small">修改</Button>
          </Space>
        )
      }
    },
  ];
  
  // 获取列表数据
  const getTableDatas = () => {
    let params = form.getFieldsValue();
    setLoading(true);
    getPromoteDetailList({
      ...params,
      page: paginationObj.current,
      per_page: paginationObj.pageSize,
    })
    .then((res) => {
      setDataSource(res.data.data.data)
      setLoading(false);
    })
    .catch((err) => {
      console.log('err: ', err);
      props.history.push({
        pathname: '/login'
      });
    });
  };
  
  // 表格选中配置
  const rowSelection = {
    onChange: (keys, rows) => {
      setSelectedRows(rows);
    },
  };

  // 查询
  const refreshList = (params) => {
    setPaginationObj({
      ...paginationObj,
      current: 1
    });
    getTableDatas();
  }

  useEffect(() => {
    getTableDatas();
  }, [paginationObj]);

  return (
    <Card style={{width: "80vw",height:'100vh',margin:'auto'}}>
      <TableSearchForm form={form} loading={loading} refreshList={ refreshList }/>
      <Table rowKey="id" bordered size="small" scroll={tableScroll} rowSelection={rowSelection} pagination={paginationObj} columns={columns} dataSource={dataSource} onChange={tableOnChange} loading={loading}/>
      <ChangeTimeModal ref={changeTimeModal}></ChangeTimeModal>
    </Card>
  )
}

export default TableDemo; 